import { useUserStore } from '@/stores/user';
// const BASE_URL = 'http://127.0.0.1:8888/api';
const BASE_URL = '/api'; // 替换为你的API基础路径

interface RequestOptions {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  header?: any;
}

const request = <T>(options: RequestOptions): Promise<T> => {
  const userStore = useUserStore();

  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        ...options.header,
        'Content-Type': 'application/json',
        Authorization: userStore.token ? `Bearer ${userStore.token}` : '',
      },
      success: (res: any) => {
        console.log('请求成功：', res);
        if (res.statusCode === 200) {
          // 根据你的API响应结构进行调整
          if (res.data.success) {
            resolve(res.data.data);
          } else {
            uni.showToast({ title: res.data.message || '请求失败', icon: 'none' });
            reject(res.data);
          }
        } else if (res.statusCode === 401) {
          // Token失效或未授权
          uni.showToast({ title: '请重新登录', icon: 'none' });
          userStore.logout();
          uni.reLaunch({ url: '/pages/login/index' });
          reject(res);
        } else {
          uni.showToast({ title: '网络错误', icon: 'none' });
          reject(res);
        }
      },
      fail: (err) => {
        console.log('请求失败：', err);
        uni.showToast({ title: '网络请求异常', icon: 'none' });
        reject(err);
      },
    });
  });
};

export default request;